package org.diancai.diancai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.diancai.diancai.entity.User;
import org.diancai.diancai.mapper.UserMapper;
import org.diancai.diancai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public String[] getPermsByUserId(Integer userId) {
        String role = userMapper.selectPermsByUserId(userId);
        return role.split(",");
    }

    // 实现Spring Security的用户加载方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 获取用户权限
        String[] perms = getPermsByUserId(user.getId());
        // 构建Spring Security的UserDetails对象
        UserBuilder builder = org.springframework.security.core.userdetails.User.withUsername(username);
        builder.password(user.getPassword()); // 数据库中存储的是加密后的密码
        builder.authorities(perms); // 权限列表
        return builder.build();
    }
}